package com.hz.controller;

import com.alibaba.fastjson.JSONObject;
import com.hz.dao.SafetyInfoDao;
import com.hz.dao.UserDao;
import com.hz.pojo.Order;
import com.hz.pojo.User;
import com.hz.service.OrderService;
import com.hz.service.SplitRecordService;
import com.hz.service.WashMachineService;
import com.hz.service.impl.SplitRecordServiceImpl;
import com.hz.service.impl.UserServiceImpl;
import com.hz.service.impl.WashMachineServiceImpl;
import com.hz.utils.DateUtils;
import com.hz.utils.MassageJson;
import com.hz.utils.MassageJsons;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/Order")
public class OrderController {

    @Resource
    private OrderService orderService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SplitRecordServiceImpl splitRecordService;
    @Resource
    WashMachineServiceImpl washMachineService;
    @Resource
    UserDao userDao;
    @Resource
    SafetyInfoDao safetyInfoDao;
    /**
     * 11111111111111111111
     * @param order_code
     * @return
     */
    @RequestMapping("/getOrderById")
    public MassageJsons getOrderById(String order_code){
        Order order = null;
        try {
            order = orderService.getOrderById(order_code);
            if(order!=null){
                String time = stringRedisTemplate.opsForValue().get(order.getOrder_code());
                return new MassageJsons("200","请求成功",order,time);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new MassageJsons("201","请求失败",null);
    }

    /**
     * 222222222222222222
     * @param user_id
     * @return
     */
    @RequestMapping("/getOrderListByUserId")
    public MassageJson getOrderListByUserId(Long user_id){
        List<Order> orderList = null;
        try {
            orderList = orderService.getOrderListByUserId(user_id);
            return new MassageJson(200,"获取成功",orderList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new MassageJson(201,"获取失败");
    }

    /**
     * 33333333333333333333333
     * 传入参数为对象时
     * 前端能传过来的值直接会自动接收到对象中
     * 无法从前端传过来的值，需要自己在controller中给对象赋值
     * @param order 订单对象
     * @return
     */
    @RequestMapping("/addOrder")
    public MassageJson addOrder(Order order){
        //获取用户对象  从用户对象获取open_id
        User user = userDao.getUserInfoUid(order.getUser_id()+"");
        //计算余额
        Double money = user.getSafetyInfo().getAccount_money()-order.getConsume_money();
        try {
            //存入数据库
            safetyInfoDao.updAccountMoney(user.getOpen_id(),money);
            //从新获取最新用户信息
            user = userDao.getUserInfo(user.getOpen_id());
            stringRedisTemplate.opsForValue().set(user.getOpen_id(),JSONObject.toJSONString(user));
        } catch (Exception e) {
            e.printStackTrace();
        }
        int i = 0;
        try {
            /**
             * 调用工具类获得当前时间，用对象 .set方法赋值为订单创建时间，也是洗衣机开始时间
             * 在从前台获取一个洗衣时间，写一个倒计时器，倒计时结束后把订单状态从进行中改成已完成
             * String order_creattime = DateUtils.getCurrentTime();
             * String wash_start_time = DateUtils.getCurrentTime();
             */

            String order_code = DateUtils.getStr(); //随机生成订单编码
            //System.out.println(order_code);
            order.setOrder_creattime(DateUtils.getCurrentTime()); //订单创建时间
            order.setWash_start_time(DateUtils.getCurrentTime()); //开始洗衣时间
            order.setOrder_state(1); //订单创建后赋默认 状态值为1
            order.setOrder_code(order_code);
            //添加结束时间
            order.setWash_end_time(DateUtils.addDateMinut(DateUtils.getCurrentTime(),order.getWash_time()));
            i = orderService.addOrder(order);

            /**
             * 调用 生成 分成记录的方法
             */
            splitRecordService.addSplitRecord(order_code);
            //修改洗衣机状态
            System.out.println(order.getWash_machine_id()+"+++++++++++++++++++++++++++++++++++++++");

            washMachineService.updWashMachineState(order.getWash_machine_id(),1L);
            /**
             * 该部分代码为  倒计时代码
             */
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {

                int midTime = order.getWash_time()*60;

                public void run() {
                    /**
                     * midTime为秒
                     * 计算小时 midTime/60=分钟 如果分钟小于60 则hh为0，如果分钟大于60 则分钟/60取整则为hh（小时数）
                     */
                    midTime--;
                    /**
                     * 把剩余时间存入Redis
                     */
                    stringRedisTemplate.opsForValue().set(order_code,midTime+"");
                    int hh = midTime / 60 / 60;
                    int mm = midTime / 60 ;
                    int ss = midTime % 60;

                    System.out.println("还剩" + hh + "小时" + mm + "分钟" + ss + "秒");

                    if(midTime<=1){
                        try {
                            /**
                             * 修改订单方法
                             */
                            orderService.updOrder(order_code,2,DateUtils.getCurrentTime());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if(midTime<=0){
                        //获取当前时间 为 结束时间 DateUtils.getCurrentTime();
                        try {
                            /**
                             * 修改订单方法
                             */

                            //执行完毕后更改洗衣机订单状态
                            washMachineService.updWashMachineState(order.getWash_machine_id(),0L);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        stringRedisTemplate.delete(order.getOrder_code());
                        timer.cancel(); //关闭
                    }
                }
            }, 1000,1000);

            if(i>0){

                return new MassageJson(200,"添加成功",user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new MassageJson(201,"添加失败",order);
    }

    /**
     * 获取洗衣剩余时间，会一直慢慢减少，直至变为0
     * @param order
     * @return
     */
    @RequestMapping("/getTime")
    public MassageJsons getOrderTime(Order order){
        String time = stringRedisTemplate.opsForValue().get(order.getOrder_code());
        return new MassageJsons("200","请求成功",time);
    }
}
